package com.smartwebee.android.blespp.blockly;

import android.util.Log;

import com.smartwebee.android.blespp.utils.Utils;

import java.util.List;

import rx.Observable;
import rx.functions.Action1;
import rx.functions.Func1;

public class BlocklyUtils {
    public static String getHexString(String originStr) {
        String s = originStr;
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (('0' <= c && c <= '9') || ('a' <= c && c <= 'f') ||
                    ('A' <= c && c <= 'F')) {
                sb.append(c);
            }
        }
        if ((sb.length() % 2) != 0) {
            sb.deleteCharAt(sb.length());
        }
        return sb.toString();
    }

    public static byte[] stringToBytes(String s) {
        byte[] buf = new byte[s.length() / 2];
        for (int i = 0; i < buf.length; i++) {
            try {
                buf[i] = (byte) Integer.parseInt(s.substring(i * 2, i * 2 + 2), 16);
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
        }
        return buf;
    }

    public static String asciiToString(byte[] bytes) {
        char[] buf = new char[bytes.length];
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < buf.length; i++) {
            buf[i] = (char) bytes[i];
            sb.append(buf[i]);
        }
        return sb.toString();
    }

    /**
     * 包装命令
     * @param originStr 原始命令
     * @return 包装后硬件可以识别的命令
     */
    public static String getSendStr(String originStr) {
        originStr = originStr.replace("\n", "\\n");
        Log.i("myOriginStr", originStr);
        StringBuilder sb = new StringBuilder();
        //开始一个Ctrl C
        sb.append("030a");

        //open File
        sb.append(Utils.addPostfixTo16("f=open('/flash/main.py', 'w')"));
        //写入文件
        sb.append(Utils.addPostfixTo16("f.write('import kq\\n" + originStr + "\\n')"));
        //关闭文件
        sb.append(Utils.addPostfixTo16("f.close()"));

        //结尾04
        sb.append("04");
        return sb.toString();
    }


    /**
     * 包装调试模式命令
     * @param originStr 原始命令
     * @return 包装后硬件可以识别的命令
     */
    public static String getDebugSendStr(String originStr) {

        originStr = originStr.replace("\n", "\\n");
        Log.i("myOriginStr", originStr);
        StringBuilder sb = new StringBuilder();
        sb.append("030a");
        //调试模式04放到前面
        sb.append("040a");
        //开始一个Ctrl C
        sb.append("030a");

        //open File
        sb.append(Utils.addPostfixTo16("f=open('/flash/debug.py', 'w')"));
        //写入文件
        sb.append(Utils.addPostfixTo16("f.write('import kq\\n" + originStr + "\\n')"));
        //关闭文件
        sb.append(Utils.addPostfixTo16("f.close()"));

        sb.append(Utils.addPostfixTo16("import debug"));

        return sb.toString();
    }
}
